﻿//https://leetcode.cn/problems/reorganize-string/

class Solution {
public:
    string reorganizeString(string s)
    {
        int hash[26] = { 0 };
        int maxchar = 0, maxcount = 0;
        for (auto ch : s)
        {
            if (maxcount < ++hash[ch - 'a'])
            {
                maxchar = ch;
                maxcount = hash[ch - 'a'];
            }
        }

        int n = s.size();
        if (maxcount > (n + 1) / 2) return "";

        string ret(n, ' ');
        int index = 0;
        for (int i = 0; i < maxcount; i++)
        {
            ret[index] = maxchar;
            index += 2;
        }

        hash[maxchar - 'a'] = 0;

        for (int i = 0; i < 26; i++)
        {
            for (int j = 0; j < hash[i]; j++)
            {
                if (index >= n) index = 1;
                ret[index] = 'a' + i;
                index += 2;
            }
        }

        return ret;

    }
};